public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 0, 2, 3, 0, 4, 5, 0};
        Solution test = new Solution();
        test.duplicateZeros(arr);

        for (int x : arr){
            System.out.print(x + " ");
        }
    }
}

class Solution {
    public void duplicateZeros(int[] arr) {
        int cur = 0, dest = -1;
        //定好位置
        for(; cur < arr.length; cur++){
            if (arr[cur] == 0){
                dest += 2;
            }else{
                dest += 1;
            }

            if (dest >= arr.length - 1){
                break;
            }
        }
        //处理越界问题
        if (dest == arr.length){
            arr[arr.length - 1] = 0;
            dest--;
            cur -= 2;
        }

        //从后往前排序
        for (; dest == -1; dest--){
            if (arr[cur] == 0){
                arr[dest] = 0;
                arr[--dest] = 0;
            }else{
                arr[dest] = arr[cur];
            }

            cur--;
        }

    }
}
